<template>
  <div
    class="home-continer"
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :style="`--innerHeight:${innerHeight}`"
  >
    <div v-if="showIndex">
      <div v-show="activeName == '0' || activeName == '1'">
        <el-row>
          <el-col :span="24">
            <Title :name="componentsName[0].name" :line="false">
              <onThing v-show="activeName == '0'" :dataArr="onThingArr" />
              <comEccount v-show="activeName == '1'" />
            </Title>
          </el-col>
        </el-row>
        <el-row style="margin-top: 10px" :gutter="10">
          <el-col :span="12">
            <Title
              class="title-area"
              :name="componentsName[1].name"
              :line="false"
            >
              <div slot="append">
                <div v-show="activeName == '0'" class="tabs-area">
                  <div class="unit">
                    <span>单位:</span>
                    <span>
                      {{ limitTabsName == "2" ? "升" : "kwh" }}
                    </span>
                  </div>
                </div>
                <div v-show="activeName == '1'" style="float: right">
                  <div class="unit">
                    <span>单位:</span>
                    <span>kgce</span>
                  </div>
                </div>
              </div>
              <el-radio-group
                class="tabs-change"
                v-show="activeName == '0'"
                v-model="limitTabsName"
                @change="handlelimitTabsChange"
                size="mini"
              >
                <el-radio-button
                  v-for="(item, index) in limitTabsArr"
                  :key="index"
                  :label="item.value"
                >
                  {{ item.label }}
                </el-radio-button>
              </el-radio-group>
              <comLimit
                ref="comLimit"
                :height="componentsName[1].height"
                v-show="activeName == '0'"
                :comLimitdata="comLimitdata"
              />
              <comReduct :activeName="activeName" v-show="activeName == '1'" />
            </Title>
          </el-col>
          <el-col :span="12">
            <Title :name="componentsName[2].name" :line="false">
              <div slot="append">
                <div v-show="activeName == '0'" style="float: right">
                  <div class="unit">
                    <span>单位:</span>
                    <span>元</span>
                  </div>
                </div>
                <div v-show="activeName == '1'" style="float: right">
                  <div class="unit">
                    <span>单位:</span>
                    <span>平方米</span>
                  </div>
                </div>
              </div>
              <comBudget
                :height="componentsName[2].height"
                :comBudgetdata="comBudgetdata"
                v-show="activeName == '0'"
              />
              <comCarb :activeName="activeName" v-show="activeName == '1'" />
            </Title>
          </el-col>
        </el-row>
        <el-row style="margin-top: 10px">
          <el-col :span="24">
            <Title :name="componentsName[3].name" :line="false">
              <div slot="append">
                <div slot="append">
                  <el-button
                    class="aps-more"
                    v-show="activeName == '0'"
                    style="float: right"
                    type="text"
                    disabled
                  >
                    更多
                  </el-button>
                </div>
                <div v-show="activeName == '1'" style="float: right">
                  <div class="unit">
                    <span>单位:</span>
                    <span>元/人年</span>
                  </div>
                </div>
              </div>
              <comTheme
                v-show="activeName == '0'"
                :themepieData="themepieData"
              />
              <comAnalyse :activeName="activeName" v-show="activeName == '1'" />
            </Title>
          </el-col>
        </el-row>
      </div>
      <div v-show="activeName == '2'">
        <oneMap v-if="activeName == '2'"></oneMap>
      </div>
      <div v-show="activeName == '3'">
        <servicenavigation></servicenavigation>
      </div>
    </div>
    <div v-else></div>
  </div>
</template>

<script>
import auth from "@/plugins/auth";
import oneMap from "@/views/visualization/oneMap.vue"; //能耗一张图
import servicenavigation from "@/views/home/servicenavigation/index.vue"; // 业务场景导航

import comTheme from "@/views/home/theme/theme.vue"; // 主题库
import comEccount from "@/views/home/eccount/eccount.vue"; // 公共双碳治理概况

import comLimit from "@/views/home/limit/limit.vue"; // 能耗当日趋势分析
import comReduct from "@/views/home/reduction/reduction.vue"; // 碳减排渠道分析

import comBudget from "@/views/home/budget/budget.vue"; // 能耗预算管控趋势分析
import comCarb from "@/views/home/carbonsink/carbonsink.vue"; // 碳汇渠道分析

// import comCons from "@/views/home/consumption/consumption.vue"; // 能耗量分析
import onThing from "@/views/home/onething/onething.vue"; // 节能降碳一件事
import comAnalyse from "@/views/home/analyse/analyse.vue"; // 负外部性内部化分析

import colorConst from "@/utils/custom-color.js";
// import webFooter from "@/components/webFooter";

import { getEnergyConsumption } from "@/api/index/index";
import { deepClone, dealElectricity } from "@/utils/index";
export default {
  name: "Index",
  components: {
    comTheme,
    comLimit,
    comBudget,
    // comCons,
    onThing,
    comEccount,
    comReduct,
    comCarb,
    comAnalyse,
    // webFooter,
    oneMap,
    servicenavigation,
  },
  dicts: ["subentry_type", "sys_dept_type"],
  data() {
    return {
      innerHeight: null,
      showIndex: false,
      // tab
      activeName: "0",
      tabArr: [
        {
          label: "能耗双控",
          value: "0",
          per: "index:energy:control",
        },
        {
          label: "双碳治理",
          value: "1",
          per: "index:carbon:governance",
        },
        {
          label: "能耗一张图",
          value: "2",
          per: "index:energy:map",
        },
      ],
      componentsName: [],
      // 能耗额度管控趋势分析
      limitTabsName: "0",
      limitTabsArr: [
        {
          label: "用电分项",
          value: "0",
        },
        {
          label: "单位能耗",
          value: "1",
        },
        {
          label: "用水分项",
          value: "2",
        },
      ],
      // 能耗分析
      consumptionTabsName: "0",
      consumptionTabsArr: [
        {
          label: "分时段",
          value: "0",
        },
        {
          label: "分部门",
          value: "1",
        },
      ],
      //! 图表数据
      themeData1: {
        quotaNum: 0, // 能耗定额管理数
        budgetNum: 0, // 能耗预算管理数
        spiksectionNum: 0, // 削峰填谷管理数
        warningNum: 0, // 能耗预警管理数
      },
      themeData2: {},
      themeData3: {
        checkNum: 0, // 考核数据数
        consultationNum: 0, // 会商数据数
      },
      subentryStatics: {},
      subentryWaterStatics: {},
      deptStatics: {},
      budgetManageStatics: {},
      daypartingUsedStatics: {},
      deptUsedStatics: {},
      // 主题库
      themepieData: {
        themepieData1: {},
        themepieData2: {},
        themepieData3: [],
      },
      // 能耗当日趋势分析
      comLimitdata: {
        subentryStatics: {},
        subentryWaterStatics: {},
        deptStatics: {},
      },
      // 能耗预算管控趋势分析
      comBudgetdata: {
        budgetManageStatics: {},
      },
      // 能耗量分析
      comConsdata: {
        daypartingUsedStatics: {},
        deptUsedStatics: {},
      },
      // 节能降碳一件事
      onThingArr: [],
      sysDepttypeArr: [],
      subentryTypeArr: [],
    };
  },
  created() {
    this.judgeRouter();
    this.judgeRole();
    if (this.$route.name === "EnergyControl") {
      this.activeName = "0";
    }
    if (this.$route.name === "CarbonGovernance") {
      this.activeName = "1";
    }
    if (this.$route.name === "EnergyMap") {
      this.activeName = "2";
    }
    if (this.$route.query.tab != undefined) {
      this.activeName = this.$route.query.tab;
    }
    this.cardNamegive();
    this.sysDepttypeArr = this.dict?.type?.sys_dept_type ?? [];
    this.subentryTypeArr = this.dict?.type?.subentry_type ?? [];
  },
  mounted() {
    setTimeout(() => {
      if (this.showIndex) {
        this.getEnergy();
      }
    }, 200);
    this.calcinnerHeight();
  },
  watch: {},
  methods: {
    calcinnerHeight() {
      this.innerHeight = window.innerHeight - 75 + "px";
    },
    judgeRouter() {
      let myRouter = this.$store.state.permission.addRoutes;
      if (myRouter.length > 0) {
        var result = myRouter.find((item) => {
          return item.path === "/work";
        });
        if (result) {
          this.showIndex = true;
        } else if (result == undefined) {
          this.showIndex = false;
        }
      } else {
        this.showIndex = false;
      }
    },
    judgeRole() {
      if (
        auth.hasRole("nhgl_user") ||
        auth.hasRole("nhgl_leader") ||
        auth.hasRole("ynbm_user") ||
        auth.hasRole("ynbm_leader") ||
        auth.hasRole("czbm_leader")
      ) {
        // this.tabArr.push({
        //   label: "业务场景导航",
        //   value: "3",
        //   per: "",
        // });
      }
    },
    // 浏览器视窗大小监控
    screenWatcher() {
      this.screenWidth = document.body.clientWidth;
      this.screenHeight = document.body.clientHeight;
      window.onresize = () => {
        return (() => {
          this.screenWidth = document.body.clientWidth;
          this.screenHeight = document.body.clientHeight;
        })();
      };
    },
    /* ......tab...... */
    handleClick(tab, event) {
      if (this.activeName == "0" || this.activeName == "1") {
        this.cardNamegive();
      }
      if (this.activeName != "3" || this.activeName != "2") {
        this.getEnergy();
      }
    },
    handlelimitTabsChange() {
      this.$refs.comLimit.getLimitdata(this.limitTabsName);
    },
    handleConTabsChange() {
      this.$refs.consumption.fatherTellmego(this.consumptionTabsName);
    },
    // 卡片名称赋予
    cardNamegive() {
      let comarr = [];
      if (this.activeName == "0") {
        comarr = [
          {
            name: "节能降碳一件事",
            class: "",
            height: 200,
          },
          {
            name: "能耗当日趋势分析",
            class: "skst-cc-day",
            height: 260,
          },
          {
            name: "能耗预算管控趋势分析",
            class: "",
            height: 260,
          },
          {
            name: "主题库",
            class: "",
            height: 200,
          },
        ];
      } else if (this.activeName == "1") {
        comarr = [
          {
            name: "公共双碳治理概况",
            class: "",
            height: 200,
          },
          {
            name: "碳减排渠道分析",
            class: "",
            height: 260,
          },
          {
            name: "碳汇渠道分析",
            class: "",
            height: 260,
          },
          {
            name: "负外部性内部化分析",
            class: "",
            height: 200,
          },
        ];
      }
      this.componentsName = comarr;
    },
    // 获取能耗双控数据
    async getEnergy() {
      this.themeData = [];
      this.$store.commit("app/updateApiCount", "add");
      await getEnergyConsumption()
        .then((res) => {
          // console.log(res, "首页统计");
          this.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          } else if (res.code === 200) {
            if (this.activeName == "0") {
              //! 能耗量分析
              // 分时段
              // this.daypartingUsedStatics = res?.data?.daypartingUsedStatics;
              // this.daypartingUsedStaticsdeal(this.daypartingUsedStatics);
              // 分部门
              // this.deptUsedStatics = res?.data?.deptUsedStatics;
              // this.deptUsedStaticsdeal(this.deptUsedStatics);
              //! 节能降碳一件事
              let totalUsedEnergy = dealElectricity(
                res?.data?.totalUsedEnergy ?? 0,
                1,
                2,
                "number"
              ); // 综合能耗
              let totalEnergyQuota = dealElectricity(
                res?.data?.totalEnergyQuota ?? 0,
                1,
                2,
                "number"
              ); // 额度总和
              let overEnergyQuota = dealElectricity(
                res?.data?.overEnergyQuota ?? 0,
                1,
                2,
                "number"
              ); // 额度超支
              let suggestMeasures = dealElectricity(
                res?.data?.suggestMeasures ?? 0,
                1,
                2,
                "number"
              ); // 建议措施
              let carbonNeutralization = dealElectricity(
                res?.data?.carbonNeutralization ?? 0,
                1,
                2,
                "number"
              ); // 碳中和
              this.onThingArr = [
                totalUsedEnergy,
                totalEnergyQuota,
                overEnergyQuota,
                suggestMeasures,
                carbonNeutralization,
              ];
              //! 能耗当日趋势分析
              // 用电分项
              this.subentryStatics = res?.data?.subentryStatics ?? {};
              this.subentryStaticsdeal(this.subentryStatics, 0);
              // 用水分项
              this.subentryWaterStatics = res?.data?.subentryWaterStatics ?? {};
              this.subentryStaticsdeal(this.subentryWaterStatics, 1);
              // 用电分区
              this.deptStatics = res?.data?.deptStatics;
              this.deptStaticsdeal(this.deptStatics);
              //! 能耗预算管控趋势分析
              this.budgetManageStatics = res?.data?.budgetManageStatics;
              this.budgetManageStaticsdeal(this.budgetManageStatics);
              //! 主题库
              // 能耗管理标准库
              this.themeData1.quotaNum = res?.data?.quotaNum ?? 0;
              this.themeData1.budgetNum = res?.data?.budgetNum ?? 0;
              this.themeData1.spiksectionNum = res?.data?.spiksectionNum ?? 0;
              this.themeData1.warningNum = res?.data?.warningNum ?? 0;
              this.themeData1deal(this.themeData1);
              // 物联能耗组织库
              this.themeData2 = res?.data?.deptTypeNum ?? {};
              this.themeData2deal(this.themeData2);
              // 能耗考核会商库
              this.themeData3.checkNum = res?.data?.checkNum ?? 0;
              this.themeData3.consultationNum = res?.data?.consultationNum ?? 0;
              this.themeData3deal(this.themeData3);
            }
          }
        })
        .catch((err) => {
          this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!20098");
        });
    },
    // 除以100
    divide100(arr) {
      arr.forEach((tig) => {
        if (tig.data.length > 0) {
          for (let i = 0; i < tig.data.length; i++) {
            tig.data[i] = dealElectricity(Number(tig.data[i]));
          }
        }
      });
    },
    // 主题库-能耗管理标准库数据处理
    themeData1deal(data) {
      // let color = ["#5B8FF9", "#5AD8A6", "#5D7092", "#F6BD16"];
      let color = colorConst.theme1;
      let dataArr = [
        { value: data.quotaNum, name: "能耗定额管理" },
        { value: data.budgetNum, name: "能耗预算管理" },
        { value: data.spiksectionNum, name: "削峰填谷管理" },
        { value: data.warningNum, name: "能耗预警标准" },
      ];
      let title = "标准规范库";
      let pieId = "themepieChartsone";
      let themepieData1 = {
        color: color,
        dataArr: dataArr,
        title: title,
        pieId: pieId,
        roseType: "radius",
        radius: ["25%", "70%"],
        position: "center",
      };
      this.themepieData.themepieData1 = themepieData1;
    },
    // 主题库-物联能耗组织库
    themeData2deal(data) {
      let xArr = data?.xaxisData ?? [];
      let yArr = data?.seriesData ?? [];
      let dataArr = [];
      if (xArr.length > 0) {
        if (this.sysDepttypeArr.length > 0) {
          this.sysDepttypeArr.map((item) => {
            let num = 0;
            xArr.map((tig) => {
              let obj = {
                name: "",
                value: "0",
              };
              if (item.value == tig) {
                obj = {
                  name: item.label,
                  value: "0",
                };
                dataArr.push(obj);
              } else {
                num++;
              }
              if (num == this.sysDepttypeArr.length) {
                obj = {
                  name: "未知",
                  value: "0",
                };
                dataArr.push(obj);
              }
            });
          });
        }
      }
      if (yArr.length > 0) {
        yArr.map((item, index) => {
          dataArr[index].value = item;
        });
      }
      let dataArr2 = [];
      if (dataArr.length > 0) {
        dataArr.map((item) => {
          if (item.name != "未知") {
            dataArr2.push(item);
          }
        });
      }
      console.log(dataArr, "dataArr");
      // let color = ["#5B8FF9", "#5AD8A6", "#5D7092", "#F6BD16", "#E8684A"];
      let color = colorConst.theme2;
      let title = "组织机构库";
      let pieId = "themepieChartstwo";
      let themepieData2 = {
        color: color,
        dataArr: dataArr2,
        title: title,
        pieId: pieId,
        radius: ["40%", "70%"],
        position: "center",
      };
      this.themepieData.themepieData2 = themepieData2;
    },
    // 主题库-能耗考核会商库
    themeData3deal(data) {
      let themepieData3 = [
        {
          name: "柴油车数",
          value: 9900,
        },
        {
          name: "新能源汽车数",
          value: 7600,
        },
        {
          name: "电消费",
          value: 6700,
        },
        {
          name: "水消费",
          value: 4600,
        },
        {
          name: "煤炭消费",
          value: 3600,
        },
      ];
      this.themepieData.themepieData3 = themepieData3;
    },
    // 能耗当日趋势分析
    subentryStaticsdeal(data, flag) {
      let seriesData = data.seriesData;
      let xaxisData = data.xaxisData;
      let yData = [];
      let xData = [];
      if (seriesData.length > 0) {
        if (this.subentryTypeArr.length > 0) {
          this.subentryTypeArr.map((tig) => {
            seriesData.map((item) => {
              let obj = {
                name: "",
                data: [],
              };
              if (item.name == tig.value) {
                obj.name = tig.label;
                obj.data = item.data;
                yData.push(obj);
              }
            });
          });
          // /100
          this.divide100(yData);
        }
      }
      if (xaxisData.length > 0) {
        xData = xaxisData;
      }
      if (flag == 0) {
        this.comLimitdata.subentryStatics = { xData: xData, yData: yData };
      } else if (flag == 1) {
        this.comLimitdata.subentryWaterStatics = { xData: xData, yData: yData };
      }
      this.handlelimitTabsChange(); // 初始化 0 用电分项
    },
    deptStaticsdeal(data) {
      let seriesData = data.seriesData;
      let xaxisData = data.xaxisData;
      // /100
      this.divide100(seriesData);
      this.comLimitdata.deptStatics = { xData: xaxisData, yData: seriesData };
    },
    // 能耗预算管控分析
    budgetManageStaticsdeal(data) {
      let seriesData = data.seriesData;
      // console.log(seriesData, 1);
      if (seriesData.length > 0) {
        seriesData.map((tig) => {
          if (tig.data.length > 0) {
            for (let i = 0; i < tig.data.length; i++) {
              tig.data[i] = (Number(tig.data[i]) / 100).toFixed(2);
            }
          }
        });
      }
      // console.log(seriesData, 2);
      let xaxisData = data.xaxisData;
      this.comBudgetdata.budgetManageStatics = {
        xData: xaxisData,
        yData: seriesData,
      };
    },
    // 能耗量分析
    daypartingUsedStaticsdeal(data) {
      let seriesData = data.seriesData;
      // console.log(seriesData, "yyyy");
      let xaxisData = data.xaxisData;
      // /100
      this.divide100(seriesData);
      this.comConsdata.daypartingUsedStatics = {
        xData: xaxisData,
        yData: seriesData,
      };
      this.handleConTabsChange(); // 分时段
    },
    deptUsedStaticsdeal(data) {
      let seriesData = data.seriesData;
      let xaxisData = data.xaxisData;
      // /100
      this.divide100(seriesData);
      this.comConsdata.deptUsedStatics = {
        xData: xaxisData,
        yData: seriesData,
      };
    },
  },
};
</script>

<style scoped lang="scss">
@import "@/assets/styles/mixin.scss";
.home-continer {
  height: var(--innerHeight);
  padding: 20px;
  // padding-bottom: 10px;
  overflow-y: scroll;
  @include scrollBar3(rgba(138, 133, 133, 0.8));
  /* 趋势分析切换tab */
  .tabs-area {
    float: right;
    width: 350px;
    z-index: 2;
    position: relative;

    .unit {
      float: right;
    }
  }
  .title-area {
    position: relative;
    .tabs-change {
      z-index: 2;
      position: absolute;
      top: 45px;
      right: 80px;
    }
  }
}
</style>
